package com.wyg.epuser.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyg.epcommonbase.common.ApiResult;
import com.wyg.epuser.entity.User;
import com.wyg.epuser.entity.UserAuth2;
import com.wyg.epuser.service.UserAuth2Service;
import com.wyg.epuser.service.UserService;
import com.wyg.epuser.utils.RequestUtil;
import com.wyg.epuser.utils.authUtil.AuthCallBack;
import com.wyg.epuser.utils.authUtil.AuthUser;
import com.wyg.epuser.utils.authUtil.gitee.GiteeAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author: WangYongGan
 * @Date: 2022/4/25 20:49
 * @Description:
 */
@Api(tags = "auth认证")
@Controller
@RequestMapping("auth")
@Slf4j
public class Auth2Controller {
    @Autowired
    GiteeAuth auth;
    @Autowired
    UserService userService;
    @Autowired
    UserAuth2Service userAuth2Service;

    @ResponseBody
    @ApiOperation("authGitee")
    @GetMapping("authGitee")
    public ApiResult authGitee(HttpServletResponse response) throws IOException {
        final String uuid = RequestUtil.getSession().getId();
        final String s = auth.urlForCode(uuid);
        //state --> sessionId
        return ApiResult.ok().data(s);
    }

    @ApiOperation("backGitee")
    @GetMapping("backGitee")
    public void giteeCallBack(AuthCallBack authCallBack, HttpServletResponse response) throws IOException {

        if (RequestUtil.logined()) {
        }
        log.info(authCallBack.toString());
        AuthUser authUser = auth.getUser(authCallBack);

        final String authCode = auth.createAuthCode(authUser.getId());
        QueryWrapper<UserAuth2> wrapper = new QueryWrapper<>();
        UserAuth2 one = userAuth2Service.getOne(wrapper.lambda().eq(UserAuth2::getAuthCode, authCode));
        User user = null;
        if (one == null) {
            //注册user
            user = new User();
            user.setPassword(UUID.randomUUID().toString());
            boolean registerCode = false;
            String username = authUser.getUsername();
            //防止重名
            for (int i = 0; i < Integer.MAX_VALUE && !registerCode; i++) {
                username = authUser.getUsername() + i;
                user.setUsername(username);
                //TODO:报错处理
                userService.register(user);
            }
            //注册 auth
            one = new UserAuth2();
            one.setAuthCode(authCode);
            user = userService.selectByName(username);
            final int uid = user.getId();
            one.setUid(uid);
            userAuth2Service.save(one);
        }
        if (user == null) {
            user = userService.getById(one.getUid());
        }
        log.info("第二步sessionId:" + RequestUtil.getSession().getId());
        //state --> sessionId  --> session
//        RequestUtil.setUserWithSession(RequestUtil.getSessionById(authCallBack.getState()), user);
        response.sendRedirect(GiteeAuth.mainUri);
    }

    @ResponseBody
    @ApiOperation("logined")
    @GetMapping("logined")
    public ApiResult logined() {
        System.out.println(RequestUtil.getUser());
        if (RequestUtil.logined())
            return ApiResult.ok().data(RequestUtil.getUser());
        return ApiResult.error();
    }
}
